<?
//分块上传
class ext_upload_large{
    private $filepath = '/Upload/tmp'; //上传目录
    private $tmpPath;  //PHP文件临时目录
    private $blobNum; //第几个文件块
    private $totalBlobNum; //文件块总数
    private $fileName; //文件名

    public function __construct(){
    }

    public function setFile($tmpPath,$blobNum,$totalBlobNum,$fileName){
        $this->tmpPath =  $tmpPath;
        $this->blobNum =  $blobNum;
        $this->totalBlobNum =  $totalBlobNum;
        $this->fileName =  $fileName;
        $this->filepath = $_SERVER['DOCUMENT_ROOT'].$this->filepath;
        
        $this->moveFile();
        $this->fileMerge();
    }
    
    //判断是否是最后一块，如果是则进行文件合成并且删除文件块
    private function fileMerge(){
        if($this->blobNum == $this->totalBlobNum){
            $fp = fopen($this->filepath.'/'. $this->fileName,"ab");    //合并后的文件名
            for($i=1; $i<= $this->totalBlobNum; $i++){
                $file_path = $this->filepath.'/'. $this->fileName.'__'.$i;
                if(file_exists($file_path)){
                    $handle = fopen($file_path,"rb");
                    fwrite($fp,fread($handle,filesize($file_path)));
                    fclose($handle);
                    unset($handle);
                }
            }
            fclose($fp);
            $this->deleteFileBlob();
        }
    }
    
   //删除文件块
    private function deleteFileBlob(){
        for($i=1; $i<= $this->totalBlobNum; $i++){
            @unlink($this->filepath.'/'. $this->fileName.'__'.$i);
        }
    }
    
    //移动文件
    private function moveFile(){
        $this->touchDir();
        $filename = $this->filepath.'/'. $this->fileName.'__'.$this->blobNum;
        move_uploaded_file($this->tmpPath,$filename);
    }
    
    //API返回数据
    public function apiReturn(){
        $data = array();
        if($this->blobNum == $this->totalBlobNum){
            if(file_exists($this->filepath.'/'. $this->fileName)){
                $data['code'] = 0;
                $data['file_path'] = $this->filepath.'/'. $this->fileName;
            }
        }else{
            if(file_exists($this->filepath.'/'. $this->fileName.'__'.$this->blobNum)){
                $data['code'] = 1;
                $data['file_path'] = '';
            }
        }
        return $data;
    }
    
    //建立上传文件夹
    private function touchDir(){
        if(!file_exists($this->filepath)){
            return mkdir($this->filepath);
        }
    }

    public function get_file_type($filename){
        $info = pathinfo($filename);
        $ext = empty($info['extension']) ? "" : $info['extension'];
        return strtolower($ext);
    }
}
